<template>
  <div class v-if="visible">
    <div class="followInfo">
      <div class="followInfobox">
        <div class="followInfo_title">跟进信息录入</div>
        <div class="task_detail">
          <div class="task_detail_header">
            <div class="task_detail_headerbox">
              <div class="title">{{ dataSource.taskName ? dataSource.taskName : '-' }}</div>
              <div class="name">
                <div class="txt">{{ dataSource.customerName ? dataSource.customerName : '-' }}</div>
                <div class="txt">{{ dataSource.carModelName ? dataSource.carModelName : '-' }}</div>
              </div>
              <img @click="handleTel(dataSource.ownerPhone)" class="tel_icon" src="@/assets/images/tel_icon.png" />
            </div>
          </div>
          <div class="follow_result">
            <div class="follow_resultbox" :style="{ width: followResultList.length * 85 + 'px' }">
              <div
                class="itembox"
                v-for="(item, index) in followResultList"
                :key="index"
                @click="handleSelectResult(index)"
                :class="resultIndex == index ? 'active' : ''"
              >
                {{ item.name }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="followInfo_content">
        <div class="followInfo_name">
          <div class="name">跟进人员：{{ formData.followPersonName }}</div>
        </div>

        <SelectRadio
          class="followInfo_item"
          :list="followTypeList"
          :label="'跟进方式'"
          :field="'followType'"
          :requireFlag="true"
          @getFieldVal="getFieldVal"
          :initVal="'phone'"
        ></SelectRadio>

        <SelectRadio
          v-if="formData.followResult == 'follow' && formData.followType == 'phone'"
          class="followInfo_item"
          :list="phoneConnectedRadio"
          :label="'电话是否接通'"
          :field="'phoneConnected'"
          :requireFlag="true"
          @getFieldVal="getFieldVal"
        >
        </SelectRadio>

        <SelectTime
          class="followInfo_item"
          :label="'跟进时间'"
          :field="'followDate'"
          :disabled="true"
          :type="'datetime'"
          :requireFlag="true"
          @getFieldVal="getFieldVal"
        ></SelectTime>

        <SelectTime
          v-if="formData.followResult == 'follow'"
          class="followInfo_item"
          :label="'下次跟进时间'"
          :field="'nextFollowDate'"
          :type="'date'"
          :requireFlag="true"
          :date-max="maxNextFollowDate"
          @getFieldVal="getFieldVal"
        ></SelectTime>

        <SelectTime
          v-if="(formData.followResult == 'success' || formData.followResult == 'xbsuccess') && dataSource.taskTypeName != '续保到期提醒'"
          class="followInfo_item"
          :label="'预约进场时间'"
          :field="'bookingInDate'"
          :type="'datetime'"
          :requireFlag="true"
          @getFieldVal="getFieldVal"
        ></SelectTime>

        <div
          class="radiobox"
          v-if="(formData.followResult == 'success' || formData.followResult == 'xbsuccess') && dataSource.taskTypeName != '续保到期提醒'"
        >
          <div class>
            <div class="card_label">
              <div class="label_txt">
                <div class="require_icon">*</div>
                <div>维修中心：</div>
              </div>
            </div>
            <div class="card_select">
              <div class="select_time" @click="handleSelect('fixCenterId', 'fixCenterName')">
                <div class="time_val">{{ formData.fixCenterName ? formData.fixCenterName : '请选择' }}</div>
                <i class="iconfont icon-right"></i>
              </div>
            </div>
          </div>
        </div>

        <div
          class="radiobox"
          v-if="(formData.followResult == 'success' || formData.followResult == 'xbsuccess') && dataSource.taskTypeName != '续保到期提醒'"
        >
          <div class>
            <div class="card_label">
              <div class="label_txt">
                <div class="require_icon">*</div>
                <div>服务顾问：</div>
              </div>
            </div>
            <div class="card_select">
              <div class="select_time" @click="handleSelect('empId', 'empName')">
                <div class="time_val">{{ formData.empName ? formData.empName : '请选择' }}</div>
                <i class="iconfont icon-right"></i>
              </div>
            </div>
          </div>
        </div>

        <SelectRadio
          v-if="formData.followResult == 'success' && dataSource.taskTypeName != '续保到期提醒'"
          class="followInfo_item"
          :list="bookingTypeList"
          :label="'预约类型'"
          :field="'bookingType'"
          :requireFlag="true"
          @getFieldVal="getFieldVal"
        ></SelectRadio>

        <SelectRadio
          v-if="formData.followResult == 'failed' || formData.followResult == 'xbfailed'"
          class="followInfo_item"
          :list="failedList"
          :label="'战败原因'"
          :field="'failed'"
          :requireFlag="true"
          @getFieldVal="getFieldVal"
        ></SelectRadio>

        <SelectInput
          v-if="
            formData.followResult == 'follow' ||
            formData.followResult == 'success' ||
            formData.followResult == 'inFollow' ||
            formData.followResult == 'xbsuccess'
          "
          class="followInfo_item"
          :label="'跟进备注'"
          :field="'followNote'"
          :requireFlag="false"
          @getFieldVal="getFieldVal"
          ref="inputRef"
        ></SelectInput>

        <SelectInput
          v-if="formData.followResult == 'failed' || formData.followResult == 'xbfailed'"
          class="followInfo_item"
          :label="'战败说明'"
          :field="'followSupple'"
          :requireFlag="true"
          @getFieldVal="getFieldVal"
        ></SelectInput>

        <div class="radiobox" v-if="dataSource.taskTypeName != '续保到期提醒'">
          <div class>
            <div class="card_label">
              <div class="label_txt">
                <div>同步关联任务：</div>
              </div>
            </div>
            <div class="card_select">
              <div class="select_time" @click="handleMoreSelect">
                <div class="time_val">{{ formData.taskNames ? formData.taskNames : '请选择' }}</div>
                <i class="iconfont icon-right"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="fixCenter_btn">
        <div class="cancel_btn" @click="closePop">取消</div>
        <div class="confirm_btn" @click="formOnSubmit">确认</div>
      </div>

      <!-- 表单 -->
      <!-- <div class="formData">
        <van-form
          @submit="formOnSubmit"
          ref="form"
        >
          <van-field
            v-model="formData.followResultName"
            name="跟进结果"
            label="跟进结果"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            readonly
            @click="handleSelect('followResult', 'followResultName')"
            required
            :rules="[{ required: true }]"
          />
          <van-field
            v-model="formData.followTypeName"
            name="跟进方式"
            label="跟进方式"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            readonly
            @click="handleSelect('followType', 'followTypeName')"
          />
          <van-field
            v-model="formData.followPersonName"
            name="跟进人员"
            label="跟进人员"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            readonly
          />

          <van-field
            readonly
            clickable
            name="跟进时间"
            :value="formData.followDate"
            input-align="right"
            label="跟进时间"
            placeholder="请选择时间"
            @click="handleSelectTime('followDate')"
            right-icon="arrow"
          />
          <van-field
            v-if="formData.followResult == 'follow'"
            readonly
            clickable
            name="下次跟进时间"
            :value="formData.nextFollowDate"
            input-align="right"
            label="下次跟进时间"
            placeholder="请选择下次跟进时间"
            @click="handleSelectTime('nextFollowDate')"
            right-icon="arrow"
            required
            :rules="[{ required: true }]"
          />
          <van-field
            v-if="
            formData.followResult == 'success' &&
            dataSource.taskTypeName != '续保到期提醒'
          "
            readonly
            clickable
            name="预约进场时间"
            :value="formData.bookingInDate"
            input-align="right"
            label="预约进场时间"
            placeholder="请选择时间"
            @click="handleSelectTime('bookingInDate')"
            right-icon="arrow"
            required
            :rules="[{ required: true }]"
          />

          <van-field
            v-if="
            formData.followResult == 'success' &&
            dataSource.taskTypeName != '续保到期提醒'
          "
            v-model="formData.fixCenterName"
            name="维修中心"
            label="维修中心"
            input-align="right"
            placeholder="请选择"
            readonly
            right-icon="arrow"
            @click="handleSelect('fixCenterId', 'fixCenterName')"
            required
            :rules="[{ required: true }]"
          />

          <van-field
            v-if="
            formData.followResult == 'success' &&
            dataSource.taskTypeName != '续保到期提醒'
          "
            v-model="formData.empName"
            name="服务顾问"
            label="服务顾问"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            @click="handleSelect('empId', 'empName')"
            readonly
            required
            :rules="[{ required: true }]"
          />
          <van-field
            v-if="
            formData.followResult == 'success' &&
            dataSource.taskTypeName != '续保到期提醒'
          "
            v-model="formData.bookingName"
            name="预约类型"
            label="预约类型"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            readonly
            @click="handleSelect('bookingType', 'bookingName')"
            required
            :rules="[{ required: true }]"
          />

          <van-field
            v-if="formData.followResult == 'failed'"
            v-model="formData.failedName"
            name="战败原因"
            label="战败原因"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            readonly
            @click="handleSelect('failed', 'failedName')"
          />

          <div
            class="voicebox"
            v-if="
            formData.followResult == 'follow' ||
            formData.followResult == 'success'
          "
          >
            <van-field
              v-model="formData.followNote"
              name="跟进备注"
              label="跟进备注"
              type="textarea"
              input-align="left"
              placeholder=""
              autosize
            />
            <i
              @click="clickRecord('followNote')"
              class="iconfont icon-voice"
            ></i>
          </div>

          <van-field
            v-if="dataSource.taskTypeName != '续保到期提醒'"
            v-model="formData.taskNames"
            name="同步关联任务"
            label="同步关联任务"
            input-align="right"
            placeholder="请选择"
            readonly
            @click="handleMoreSelect()"
            right-icon="arrow"
          />
          <div
            class="voicebox"
            v-if="formData.followResult == 'failed'"
          >
            <van-field
              v-model="formData.followSupple"
              name="战败说明"
              label="战败说明"
              type="textarea"
              input-align="left"
              placeholder=""
              autosize
            />
            <i
              @click="clickRecord('followSupple')"
              class="iconfont icon-voice"
            ></i>
          </div>
        </van-form>
      </div>-->
      <van-popup v-model="showSelectPicker" position="bottom">
        <van-field
          name="模糊查询"
          input-align="left"
          v-model="likeWho"
          label="模糊查询"
          v-if="likeWhoField == 'empId' || likeWhoField == 'fixCenterId'"
          placeholder="请输入模糊查询关键词"
        />
        <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
      </van-popup>
      <TaskMultipleSelect
        :visible="showMultipleVisible"
        @close="showMultipleVisible = false"
        @multipleSubmit="multipleSubmit"
        :value="formData.billId"
        :list="relevanceList"
      ></TaskMultipleSelect>
      <Voice :record-box="recordBox" @translateResult="getWords" @changeRecordBox="closeRecord" />
    </div>
    <div class="mask" @click.stop="closePop"></div>
  </div>
</template>

<script>
import { DatetimePicker, Field, Form, Notify, Tab, Tabs, Toast } from 'vant'
import carApi from '@/api/carApi'
import taskApi from '@/api/taskApi'
import { getCookies, getCurrentDetailMin, isPhone } from '@/utils/util.js'
import commonApi from '@/api/commonApi'
import TaskMultipleSelect from '@/components/TaskMultipleSelect/index'
import Voice from '../voice'
import SelectRadio from './SelectRadio'
import SelectTime from './SelectTime'
import SelectInput from './SelectInput'

export default {
  name: 'FollowEdit',
  components: {
    Field,
    Form,
    DatetimePicker,
    Tab,
    Tabs,
    Toast,
    TaskMultipleSelect,
    Voice,
    SelectRadio,
    SelectTime,
    SelectInput,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    billId: {
      type: String,
      default: null,
    },
    dataSource: {
      type: Object,
      default: {},
    },
    pageType: {
      type: Number,
      default: 0,
    },
    maxNextFollowDate: {
      type: Date,
      default: '',
    }
  },
  data() {
    return {
      showTimerPicker: false,

      formData: {
        followResult: '', //跟进结果，String，必填
        followResultName: '',
        followType: 'phone', //跟进类型,必填，String
        followTypeName: '', //跟进类型,必填，String
        billId: '', //父ID,必填，String
        followDate: getCurrentDetailMin(), // 跟进时间，必填
        nextFollowDate: '', //下次跟进时间，必填
        followNote: '', //跟进备注，必填
        failed: '', //战败原因，跟进结果是战败时必填
        followSupple: '', //战败补充
        userId: '', //用户ID，必填，String
        bookingType: '',
        bookingName: '',
        bookingInDate: '',
        taskNames: '',
        fixCenterId: '', //预约维修中心ID值,跟进结果是成功时必填
        fixCenterName: '',
        empId: '', //预约服务顾问id,跟进结果是成功时必填
        empName: '',
        phoneConnected: '', //电话是否接通，跟进类型是电话时必填
        // materialPriceId: "", //配件价格类型id,跟进结果是成功时必填
        // materialPriceIdName: "",
        // repairpricetypeId: "", //维修价格类型id,跟进结果是成功时必填
        // repairpricetypeIdName: "",
        // workBillType: "", //预约工单类型，跟进结果是成功时必填
        // workBillTypeName: "",
      },
      columns: [],
      showSelectPicker: false,
      detailId: '',
      userId: getCookies('userId'), //用户ID，必填，String
      currentDate: new Date(),
      followResultList: [],
      followTypeList: [],
      followPersonList: [],
      failedList: [],
      bookingTypeList: [],
      relevanceList: [],
      relevanceParams: {
        codeNo: '', //车架号或者车牌号，String，必填
        pageNo: 1, //当前页数，默认从1开始，每页显示十条，int，不能为空或者小于1
        oneBillStatus: 'unDeal', //任务一级状态
        twoBillStatus: '', //任务二级状态
        taskTypeId: '', //任务类型ID值
        taskPersonId: '', //任务跟进人，ID值
        fixCenterId: '',
        serverPsnId: '',
        taskStartCreateTime: '',
        taskEndCreateTime: '',
        isExceed: '', //是否逾期，1为是，0为否
        isGenRepBook: '', //是否生成维修预约单
        billId: '', //本身单据ID，此为详细界面使用
        carId: '', //车辆ID，此为详细界面使用
        userId: getCookies('userId'), //用户ID，必填，String
        isFactTask: '', //是否厂家任务
        isHuiYuan: '', //是否会员客户
        isHYCar: '', //是否会员绑定车辆
      },
      showMultipleVisible: false,
      fixCenterList: [],
      workBillTypeList: [],
      repairpricetypeList: [],
      materialPriceList: [],
      userInfo: getCookies('userInfo'),
      empList: [],
      // maxDate: new Date(2024, 0, 17, 20, 20),
      maxDate: '',
      recordBox: false,
      recordName: '',
      likeWho: '',
      likeWhoField: '',
      carInfo: {},
      resultIndex: null,
      phoneConnectedRadio: [{name: '是', value: 1}, {name: '否', value: 0}]
    }
  },

  mounted() {
    if (localStorage.getItem('followId')) {
    }
  },
  watch: {
    visible: {
      handler: function (val, oldVal) {
        if (val) {
          this.formData.followPersonName = JSON.parse(getCookies('userInfo')).kdusername
          this.formData.followPersonId = this.userId

          this.formData.billId = ''
          this.formData.taskNames = ''

          this.getFollowResult()
          this.getFollowType()
          this.getEmpPerson()
          this.getRelevanceTask()
        }
      },
      deep: true,
      immediate: false,
    },
    'formData.followResult': {
      handler: function (val, oldVal) {
        if (val) {
          this.clearData()
          if (val == 'failed' || val == 'xbfailed') {
            this.getTaskFailed()
          }
          if (val == 'success' || val == 'xbsuccess') {
            this.getBookingTypeList()
            this.getMainFixCenter()
          }
        }
      },
      deep: true,
      immediate: false,
    },
    'formData.fixCenterId': {
      handler(val, OldVal) {
        if (val) {
          this.getServiecePerson()
        }
      },
      deep: true,
    },
    likeWho: function (nval, oval) {
      if (this.likeWhoField == 'fixCenterId') {
        if (nval) {
          let newArr = this.fixCenterList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          this.columns = newArr
        } else {
          this.columns = this.fixCenterList
        }
      }
      if (this.likeWhoField == 'empId') {
        if (nval) {
          let newArr = this.empList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          this.columns = newArr
        } else {
          this.columns = this.empList
        }
      }
    },
  },
  methods: {
    handleSelectResult(index) {
      this.resultIndex = index
      this.formData.followResult = this.followResultList[index].value
    },
    getFieldVal(field, value) {
      console.log(field)
      console.log(value)
      this.formData[field] = value
      if (field == 'followType') {
        this.formData.phoneConnected = ''
      }
      console.log(this.formData)
    },
    // 点击录音
    clickRecord(name) {
      this.recordName = name
      this.recordBox = true
    },
    // 获取录音转文字
    getWords(data) {
      const formdata = this.formData
      formdata[this.recordName] = formdata[this.recordName] + data
    },
    // 关闭录音弹窗
    closeRecord(data) {
      this.recordBox = data
    },
    getCurTime() {
      let currentDate = new Date()
      this.maxDate = new Date(
        currentDate.getFullYear(),
        currentDate.getMonth(),
        new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate(),
        23,
        59
      )
    },
    // getDetail(billId) {
    //   taskApi.getCustomerTaskById({ billId, userId: this.userId }).then((res) => {
    //     this.dataSource = res.data
    //     this.formData.billId = this.dataSource.billId
    //   })
    // },

    // 车辆详情
    getCarInfoBase(id) {
      carApi.getCarInfoBase({ id }).then((res) => {
        if (res.code == 1) {
          this.carInfo = res.data
          this.formData.fixCenterId = res.data.fixCenterId
          this.formData.fixCenterName = res.data.fixCenterName
          this.getServiecePerson2()
        }
      })
    },
    // 获取跟进结果
    getFollowResult() {
      commonApi
        .getEnums({ key: 'followResult', userId: this.userId, isAddCustomerFollow: true, customerTaskId: this.dataSource.billId })
        .then((res) => {
          if (res.data) {
            // let followResultList = []

            // res.data.forEach((item, index) => {
            //   if (this.dataSource.taskTypeName == '续保到期提醒') {
            //     if (item.value == 'follow' || item.value == 'xbsuccess' || item.value == 'xbfailed') {
            //       followResultList.push(item)
            //     }
            //   } else {
            //     if (item.value == 'follow' || item.value == 'failed' || item.value == 'success' || item.value == 'inFollow')
            //       followResultList.push(item)
            //   }
            // })
            // this.followResultList = followResultList
            this.followResultList = res.data
            this.followResultList.forEach((item, index) => {
              if (item.value == 'follow') {
                this.resultIndex = index
                this.formData.followResult = item.value
              }
            })
          }
        })
    },
    // 获取跟进方式
    getFollowType() {
      commonApi
        .getEnums({ key: 'followType', userId: this.userId, isAddCustomerFollow: true, customerTaskId: this.dataSource.billId })
        .then((res) => {
          if (res.data) {
            this.followTypeList = res.data
          }
        })
    },
    // 获取战败原因
    getTaskFailed() {
      commonApi
        .getEnums({ key: 'taskFailed', userId: this.userId, isAddCustomerFollow: true, customerTaskId: this.dataSource.billId })
        .then((res) => {
          if (res.data) {
            this.failedList = res.data
          }
        })
    },

    // 跟进人员
    getEmpPerson() {
      commonApi
        .getEmpPerson({
          fixCenterId: '',
          userId: this.userId,
          type: 'followPerson',
        })
        .then((res) => {
          if (res.data) {
            this.followPersonList = res.data
          }
        })
    },
    // 获取服务人员
    getServiecePerson() {
      commonApi
        .getEmpPerson({
          fixCenterId: this.formData.fixCenterId,
          userId: this.userId,
          type: 'taskFollow',
        })
        .then((res) => {
          if (res.data) {
            this.empList = res.data
          }
        })
    },
    // 获取服务人员
    getServiecePerson2() {
      commonApi
        .getEmpPerson({
          fixCenterId: this.formData.fixCenterId,
          userId: this.userId,
          type: 'taskFollow',
        })
        .then((res) => {
          if (res.data) {
            this.empList = res.data
            this.formData.empId = this.carInfo.serverPsnId
            this.formData.empName = this.carInfo.serverPsnName
          }
        })
    },
    // 获取预约类型

    getBookingTypeList() {
      commonApi
        .getEnums({
          key: 'bookingType',
          userId: this.userId,
          isAddCustomerFollow: true,
          customerTaskId: this.dataSource.billId,
        })
        .then((res) => {
          if (res.data) {
            this.bookingTypeList = res.data
          }
        })
    },
    // 关联任务
    getRelevanceTask() {
      taskApi
        .getCustomerTaskList({
          ...this.relevanceParams,
          codeNo: this.dataSource.vinCode,
          billId: this.dataSource.billId,
          fixCenterId: this.dataSource.fixCenterId,
        })
        .then((res) => {
          this.relevanceList = res.data
        })
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      if (field == 'followResult') {
        this.columns = this.followResultList
      } else if (field == 'followType') {
        this.columns = this.followTypeList
      } else if (field == 'followPersonID') {
        this.columns = this.followPersonList
      } else if (field == 'failed') {
        this.columns = this.failedList
      } else if (field == 'bookingType') {
        this.columns = this.bookingTypeList
      } else if (field == 'fixCenterId') {
        this.columns = this.fixCenterList
        this.getServiecePerson()
      } else if (field == 'workBillType') {
        this.columns = this.workBillTypeList
      } else if (field == 'repairpricetypeId') {
        this.columns = this.repairpricetypeList
      } else if (field == 'materialPriceId') {
        this.columns = this.materialPriceList
      } else if (field == 'empId') {
        this.columns = this.empList
      }
      this.likeWhoField = field
      this.field = field
      this.fieldName = fieldName
      this.showSelectPicker = true
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      if (this.field == 'materialPriceId' || this.field == 'repairpricetypeId' || this.field == 'fixCenterId' || this.field == 'empId') {
        this.formData[this.field] = value.billId
      } else {
        this.formData[this.field] = value.value
      }

      this.formData[this.fieldName] = value.name

      if (this.field == 'followResult' && value.name == '邀约成功') {
        this.getCarInfoBase(this.dataSource.carId)
      }
      if (this.field == 'fixCenterId') {
        this.formData.empId = ''
        this.formData.empName = ''
      }
      this.likeWho = ''
      this.likeWhoField = ''
      this.showSelectPicker = false
    },
    handleMoreSelect() {
      this.showMultipleVisible = true
    },
    // 多选确认
    multipleSubmit(data) {
      if (data && data.length != 0) {
        let arr = []
        arr.push(this.dataSource.billId)

        this.formData.taskNames = data.map((item) => item.taskName).join(',')
        let ids = data.map((item) => item.billId)
        ids.forEach((item) => {
          arr.push(item)
        })
        this.formData.billId = arr.join(';')
      } else {
        this.formData.billId = this.dataSource.billId
        this.formData.taskNames = ''
      }
    },

    onConfirm(val, field) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[field] = `${year}-${month}-${day} ${hour}:${minute}:00`
      this.showTimerPicker = false
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      }
      //  else if (type === "second") {
      //   return `${value}秒`;
      // }
      return value
    },
    // 时间选择
    handleSelectTime(field) {
      if (field == 'followDate') {
        this.getCurTime()
      } else {
        this.maxDate = new Date(2030, 11, 30, 23, 59)
      }
      this.timeField = field
      this.showTimerPicker = true
    },
    onTimeConfirm(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[this.timeField] = `${year}-${month}-${day} ${hour}:${minute}`
      this.showTimerPicker = false
    },
    //维修预约
    applyRepair() {
      this.$router.push('/applyRepair')
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val
        })
        if (obj.length > 0) {
          return obj[0].name
        }
      }
      return null
    },
    // 判断时间是否大于1个月
    isOverOneMonth(startDateStr, endDateStr, num) {
      var start = new Date(startDateStr) // 将起始日期字符串转换为 Date 对象
      var end = new Date(endDateStr) // 将结束日期字符串转换为 Date 对象
      var diffTime = Math.abs(end - start) // 计算两个日期相差的毫秒数
      var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) // 将毫秒数转换成天数并向上取整
      return diffDays > num * 30 // 如果相差的天数大于30天则返回 true，表示超过了一个月；反之返回 false
    },

    formOnSubmit() {
      console.log(this.vaiFormdata())
      if (!this.vaiFormdata()) {
        return
      }
      if (this.formData.followResult == 'follow' && this.isOverOneMonth(this.formData.followDate, this.formData.nextFollowDate, 3)) {
        Notify({
          type: 'danger',
          message: '下次跟进时间不能超过跟进时间三个月',
        })
        return
      }

      if (this.formData.followResult == 'success' && this.isOverOneMonth(this.formData.followDate, this.formData.bookingInDate, 1)) {
        Notify({
          type: 'danger',
          message: '预约进场时间不能超过跟进时间一个月',
        })
        return
      }

      // if (this.formData.followNote == '') {
      //   this.formData.followNote = `由【${this.dataSource.taskName}${
      //     this.formData.taskNames ? '、' + this.formData.taskNames : ''
      //   }】,关联生成，任务跟进人：${JSON.parse(this.userInfo).kdusername}`
      // }

      let data = JSON.parse(JSON.stringify(this.formData))
      data.bookingInDate = data.bookingInDate ? data.bookingInDate + ':00' : ''
      data.nextFollowDate = data.nextFollowDate ? data.nextFollowDate + ' 00:00:00' : ''
      data.followDate = data.followDate ? data.followDate + ':00' : ''
      if (data.followResult != 'follow') {
        data.nextFollowDate = ''
      }
      Toast.loading({
        message: '提交中...',
        forbidClick: true,
        overlay: true,
      })
      taskApi
        .addNewCustomerTaskFollow({
          ...data,
          billId: this.formData.billId ? this.formData.billId : this.dataSource.billId,
        })
        .then((res) => {
          if (!res.msg) {
            Toast.clear()
            this.$notify({
              message: '添加成功',
              type: 'success',
            })
            this.$emit('close')

            if (this.pageType && this.pageType == 1) {
              this.$emit('initData')
            } else {
              this.$parent.getDetail(this.dataSource.billId)
              localStorage.setItem('taskFollowId', this.formData.billId ? this.formData.billId : this.dataSource.billId)
            }
          } else {
          }
        })
      // this.$refs.form
      //   .validate()
      //   .then(() => {

      //   })
      //   .catch(() => {
      //     this.$toast.fail('请完善信息')
      //   })
    },

    // 校验方法
    vaiFormdata() {
      let formData = this.formData
      if (!formData.followType) {
        Toast('请选择跟进方式')
        return false
      }
      if (!formData.followDate) {
        Toast('请选择跟进时间')
        return false
      }

      // 持续跟进校验
      if (formData.followResult == 'follow') {
        if (this.formData.followType =='phone') {
          if (this.formData.phoneConnected == null || this.formData.phoneConnected === '') {
            Toast('请选择电话是否接通')
            return false
          }
        }
        if (!formData.nextFollowDate) {
          Toast('请选择下次跟进时间')
          return false
        }
        if (!formData.followNote) {
          Toast('请填写跟进备注')
          return false
        }
        return true
      }

      // 本次战败校验
      if (formData.followResult == 'failed' || formData.followResult == 'xbfailed') {
        if (!formData.failed) {
          Toast('请选择战败原因')
          return false
        }
        if (!formData.followSupple) {
          Toast('请填写战败说明')
          return false
        }
        return true
      }

      // 邀约成功
      if (formData.followResult == 'success') {
        if (!formData.bookingInDate) {
          Toast('请选择预约进场时间')
          return false
        }
        if (!formData.fixCenterId) {
          Toast('请选择维修中心')
          return false
        }
        if (!formData.empId) {
          Toast('请选择服务顾问')
          return false
        }
        if (!formData.bookingType) {
          Toast('请选择预约类型')
          return false
        }
        if (!formData.followNote) {
          Toast('请填写跟进备注')
          return false
        }
        return true
      }

      // 持续跟进校验
      if (formData.followResult == 'inFollow') {
        if (!formData.followNote) {
          Toast('请填写跟进备注')
          return false
        }
        return true
      }

      // 持续跟进校验
      if (formData.followResult == 'xbsuccess') {
        if (!formData.followNote) {
          Toast('请填写跟进备注')
          return false
        }
        return true
      }
      return true
    },
    handleTel(tel) {
      if (isPhone()) {
        window.location.href = `tel:${tel}`
      } else {
        Toast('请在手机端使用此功能')
      }
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          type: 'fixCenter',
        })
        .then((res) => {
          this.fixCenterList = res.data
          res.data.forEach((item, index) => {
            if (item.billId == getCookies('orgId')) {
              this.formData.fixCenterId = item.billId
              this.formData.fixCenterName = item.name
            }
          })
        })
    },

    // 获取工单类型
    // getWorkBillType() {
    //   commonApi
    //     .getEnums({
    //       key: "workBillTypeNew",
    //     })
    //     .then((res) => {
    //       if (res.data) {
    //         this.workBillTypeList = this.formatCheckData(res.data);
    //       }
    //     });
    // },
    // 获取预约类型
    getBookingTypeList() {
      commonApi
        .getEnums({
          key: 'bookingType',
          userId: this.userId,
          isAddCustomerFollow: true,
          customerTaskId: this.dataSource.billId,
        })
        .then((res) => {
          if (res.data) {
            this.bookingTypeList = res.data
          }
        })
    },
    // 获取维修价格
    // getRepairpricetype() {
    //   commonApi.getRepairpricetype({}).then((res) => {
    //     if (res.data) {
    //       this.repairpricetypeList = res.data;
    //       res.data.forEach((item) => {
    //         if (item.name == "标准单价") {
    //           this.formData.repairpricetypeId = item.billId;
    //         }
    //       });
    //     }
    //   });
    // },
    // 获取配件价格
    // getMaterialPriceType() {
    //   commonApi
    //     .getMaterialPriceType({ fixCenterId: localStorage.getItem("orgId") })
    //     .then((res) => {
    //       if (res.data) {
    //         this.materialPriceList = res.data;
    //         res.data.forEach((item) => {
    //           if (item.name == "标准价格") {
    //             this.formData.materialPriceId = item.billId;
    //           }
    //         });
    //       }
    //     });
    // },
    // 格式化多选数据
    formatCheckData(data) {
      data.forEach((item) => {
        item.check = false
      })
      return data
    },
    closePop() {
      this.$emit('close')
    },
    clearData() {
      this.formData.failed = ''
      this.formData.nextFollowDate = ''
      this.formData.bookingInDate = ''
      this.formData.fixCenterId = ''
      this.formData.fixCenterName = ''
      this.formData.empName = ''
      this.formData.empId = ''
      this.formData.bookingType = ''
      this.formData.followNote = ''
      this.formData.followSupple = ''
      if (this.$refs.inputRef && this.$refs.inputRef.txtVal) {
        this.$refs.inputRef.txtVal = ''
      }
    },
  },
}
</script>

<style lang="less" scoped>
body {
  // background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  background: #f3f3f3;
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .carStatus {
          border: 1px solid #35bc04;
          color: #35bc04;
          border-radius: 5px;
          padding: 0.1rem 0.1rem;
          font-size: 0.24rem;
          text-align: center;
          margin-left: 0.1rem;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
        .name {
          border-right: 2px solid #ccc;
          padding-right: 0.1rem;
          margin-right: 0.1rem;
        }
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
    }
  }
  .formData {
    background: #fff;
    overflow: hidden;
  }
}

.submitBtn {
  background: #409eff;
  color: #fff;
  width: 75%;
  margin: auto;
  text-align: center;
  padding: 0.25rem;
  border-radius: 5px;
  margin-top: 0.6rem;
  font-size: 0.3rem;
  margin-bottom: 0.5rem;
}
.voicebox {
  position: relative;
  .icon-voice {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: 20px;
    color: #409eff;
  }
}
.task_detail {
  // margin-top: 50px;
  .task_detail_header {
    padding: 17px 0 10px;
    background: #fff;
    // margin-bottom: 10px;
    border-bottom: 1px solid #f1f1f1;
    position: relative;

    .title {
      text-align: center;
      //font-family: Alibaba;
      font-weight: 700;
      font-size: 16px;
      color: #333333;
      max-width: 70%;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      margin: auto;
    }
    .name {
      display: flex;
      text-align: center;
      width: 100%;
      justify-content: center;
      margin-top: 10px;

      .txt {
        //font-family: Alibaba;
        font-weight: 400;
        font-size: 12px;
        color: #999999;
        text-align: center;
        margin-right: 10px;
      }
    }
    .tel_icon {
      position: absolute;
      top: 16px;
      right: 10px;
      width: 29px;
    }
  }
  .follow_result {
    padding: 10px;
    // border-bottom: 6px solid #f7f7f7;
    border-bottom: 1px solid #f7f7f7;
    max-width: 96%;
    overflow: auto;
    &::-webkit-scrollbar {
      display: none;
    }
    .follow_resultbox {
      display: flex;
    }

    .itembox {
      font-weight: 400;
      font-size: 12px;
      color: #4e5969;
      border-radius: 32px 32px 32px 32px;
      background: #f7f7f7;
      padding: 8px 10px;
      margin-right: 10px;
      &.active {
        color: #165dff;
        background: #d8e3ff;
        border-radius: 32px 32px 32px 32px;
      }
    }
  }

  .tabbox {
    // padding: 0 10px;
    padding-top: 15px;
    border-top: 1px solid #f7f5f5;
    margin-top: 15px;
    position: relative;
    width: 7.5rem;
    overflow: hidden;
    .tab_list {
      width: 10rem;
      overflow-x: auto;
      clear: both;
      .tab_item {
        font-weight: 400;
        font-size: 14px;
        color: #4e5969;
        text-align: center;
        background: #f7f7f7;
        border-radius: 32px;
        padding: 8px 16px;
        margin-right: 6px;
        cursor: pointer;
        float: left;
        &:last-child {
          margin-right: 0;
        }
        &.active {
          color: #165dff;
          text-align: center;
          background: #d8e3ff;
        }
      }
    }
  }
}

.followInfo {
  position: fixed;
  width: 100%;
  height: calc(100vh - 116px);
  overflow: auto;
  bottom: 0;
  left: 0;
  z-index: 102;
  box-shadow: 0px 1px 0px 0px rgba(40, 47, 56, 0.04);
  border-radius: 10px 10px 0px 0px;
  background: #fff;
  &::-webkit-scrollbar {
    display: none;
  }
  .followInfobox {
    border-radius: 10px 10px 0px 0px;
    position: fixed;
    top: 116px;
    left: 0;
    width: 100%;
    background: #fff;
  }
  .followInfo_title {
    text-align: center;
    padding: 10px;
    border-bottom: 1px solid #f2f2f2;
    font-weight: 600;
    font-size: 17px;
    color: #1d2129;
  }

  .followInfo_content {
    padding: 10px;
    border-top: 6px solid #f7f7f7;
    margin-bottom: 60px;
    margin-top: 155px;
    .followInfo_item {
      margin-bottom: 10px;
    }

    .followInfo_name {
      margin-bottom: 10px;
      .name {
        width: 100px;
        padding: 5px 8px;
        font-weight: 700;
        font-size: 10px;
        color: #165dff;
        background: #e8f5ff;
        border-radius: 2px 2px 2px 2px;
      }
    }
  }
}
.mask {
  position: fixed;
  width: 100%;
  height: 100vh;
  bottom: 0;
  left: 0;
  z-index: 101;
  background: rgba(0, 0, 0, 0.5);
}
.radiobox {
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.02);
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #f4f4f6;
  padding: 8px 17px 20px 17px;
  .card_label {
    display: flex;
    margin-bottom: 10px;
    .require_icon {
      font-weight: 400;
      font-size: 12px;
      color: #ff4848;
    }
    .label_txt {
      font-weight: 400;
      font-size: 12px;
      display: flex;
      color: #86909c;
    }
  }
  .card_select {
    display: flex;
    flex-wrap: wrap;
    .radio_item {
      width: 33%;
      display: flex;
      align-items: center;
      .item_icon {
        width: 18px;
        display: block;
        margin-right: 10px;
      }
      .item_name {
        font-weight: 600;
        font-size: 12px;
        color: #2f2f2f;
      }
    }
    .select_time {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .time_val {
        font-weight: 700;
        font-size: 12px;
        color: #2f2f2f;
      }
      .icon-right {
        font-size: 16px;
        color: #c9cdd4;
      }
    }
  }
}
.fixCenter_btn {
  display: flex;
  width: 100%;
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  left: 0;
  background: #fff;
  .cancel_btn {
    width: 50%;
    font-weight: 400;
    font-size: 18px;
    color: #1d2129;
    border-right: 1px solid #e5e6eb;
    padding: 12px;
    text-align: center;
  }
  .confirm_btn {
    font-weight: 400;
    width: 50%;
    font-size: 18px;
    color: #165dff;
    padding: 12px;
    text-align: center;
  }
}
</style>
